import cryptoJs from "crypto-js";
import {encrypt,decrypt,_getRandomString,sign} from "./encrypter.js"
// export let baseURL = "http://192.168.110.86/app/" //高钰昌接口
export let baseURL = "http://admin-colorful.fulezhenxuan.cn/app/" 	//测试接口
// export let baseURL = "https://api.fulezhenxuan.cn/app/" //正式接口
var domain = baseURL.indexOf("colorful");
// var domain = baseURL.indexOf("app");
// console.log(domain);
const envflag = false //是否开启加密解密
export const aesKey = 'ld1xk2vv5yh5oj54'; // 请替换为你的AES密钥 
const aesIV = _getRandomString(16); // 使用随机生成的IV
export const myRequest = (options) => {
	const obj = options.data
	// const signobj=sign(options.data,"f4b9d14f90ef299a52f81c272089fa93")
	// console.log(signobj,998989)
	obj.token = uni.getStorageSync("token") || ''
	// console.log(obj);
	const objjson = encrypt(JSON.stringify(obj), aesKey, aesIV)
	// console.log(aesIV + objjson);
	return new Promise((resolve, reject) => {
		// uni.showLoading({
		// 	title: '加载中'
		// });
		uni.request({
			url: baseURL + options.url,
			method: options.method || 'GET',
			data: envflag ? {encryptedData: aesIV + objjson } : obj,
			header: {
				'content-type': "application/x-www-form-urlencoded",  
			},
			success: (res) => {
				// console.log(res);
				// uni.hideLoading()
				uni.stopPullDownRefresh();
				if (domain == -1) {
					// console.log('正式域名');
					// console.log = () => {};//关闭所有打印
					const encryptedResponse = res.data.encryptedData;
					const data = decrypt(encryptedResponse.slice(16), aesKey,encryptedResponse.slice(0, 16));
					// console.log(data);
					resolve(data);
					if (data.code == 0) {
						uni.$u.toast(data.msg);
					} else if (data.code == -1) {
						uni.$u.toast(data.msg);
						uni.removeStorageSync('token')
						setTimeout(() => {
							uni.navigateTo({
								url: '/pages/login/login'
							})
						}, 1500)
					}
				} else {
					resolve(res.data);
					// console.log('ce试域名');
					// console.log = () => {};//关闭所有打印
					resolve(res.data);
					 if (envflag || res.data.code == 0) {
						uni.$u.toast(res.data.msg);
					} else if (res.data.code == -1) {
						uni.$u.toast(res.data.msg);
						uni.removeStorageSync('token')
						setTimeout(() => {
							uni.navigateTo({
								url: '/pages/login/login'
							})
						}, 1500)
					}
				}
			},
			fail: (err) => {
				uni.hideLoading()
				uni.$u.toast('服务器请求失败')
				reject(err);
			}
		});
	});
};